package org.afk.sisy.gui.swing;

import java.awt.*;

import javax.swing.*;

import org.afk.tools.log.*;

public class SwingErrorHandler implements ErrorHandler
{

	static final int DEBUG = 0;
	static final int INFO = 1;
	static final int ERROR = 0;
	final JLabel status;
	private Throwable lastError;

	public Throwable getLastError()
	{
		return lastError;
	}

	public SwingErrorHandler(final JLabel status)
	{
		this.status = status;
	}

	@Override
	public void debug(final String message)
	{
		SwingUtilities.invokeLater(new Status(status, message, DEBUG));

	}

	@Override
	public void info(final String message)
	{
		SwingUtilities.invokeLater(new Status(status, message, INFO));

	}

	@Override
	public void warning(final String message)
	{
		SwingUtilities.invokeLater(new Status(status, message, ERROR));
	}

	@Override
	public void warning(final String message, final Throwable t)
	{
		if (t != null)
			warning(t);
		if (message != null)
			warning(message);
	}

	@Override
	public void warning(final Throwable t)
	{
		SwingUtilities.invokeLater(new Status(status, t.getLocalizedMessage(), ERROR));
		t.printStackTrace();
		lastError = t;
	}

}

class Status implements Runnable
{

	private final String message;
	private final int level;
	private final JLabel status;

	public Status(final JLabel status, final String message, final int debug)
	{
		this.message = message;
		this.level = debug;
		this.status = status;
	}

	@Override
	public void run()
	{
		status.setText(message);
		if (level == SwingErrorHandler.DEBUG)
			status.setForeground(Color.lightGray);
		if (level == SwingErrorHandler.INFO)
			status.setForeground(Color.gray);
		if (level == SwingErrorHandler.DEBUG)
			status.setForeground(Color.black);
	}

}
